﻿using System;
using System.Collections.Specialized;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using Medianamik.Core;
using System.Text;
using System.Collections;
using Medianamik.Globalization;
using System.Collections.Generic;
using System.Diagnostics;

namespace Medianamik.UI 
{
    public class Utility 
	{
		private static string _assemblyVersion;
        private static string _fileVersion;
        private static string _codeName;
        /// <summary>
        /// Obtenir la version de Médianamik.UI
        /// </summary>
        /// <returns></returns>
        public static String GetAssemblyVersion()
        {
			if (_assemblyVersion == null)
			{
				_assemblyVersion =  System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
			}
			return _assemblyVersion;
        }

        public static String GetFileVersion()
        {
            if(_fileVersion == null)
            {
                _fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
            }

            return _fileVersion;

        }

        public static String GetCodeName()
        {
            if (_codeName == null)
            {
                _codeName = string.Empty;
                var attributes = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);
                if (attributes.Length == 1)
                {
                    var attribute = attributes[0] as AssemblyInformationalVersionAttribute;
                    if (attribute != null)
                    {
                        _codeName = attribute.InformationalVersion;
                    }
                }
            }
            return _codeName;
        }

        /// <summary>
        /// Obtenir la date courante en format AAAA-MM-JJ
        /// </summary>
        /// <returns></returns>
        public static String GetCurrentDate()
        {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// Obtenir la signature du Copyright
        /// </summary>
        /// <returns></returns>
        public static String GetCopyright()
        {
            return "2004-" + DateTime.Now.Year.ToString();
        }

        /// <summary>
        /// Trouver récursivement un contrôle
        /// </summary>
        /// <param name="root">Container racince</param>
        /// <param name="id">Contrôle recherché</param>
        /// <returns>Contrôle trouvé, null sinon</returns>
        public static Control FindControlRecursive(Control root, string id)
        {
            
            if (root.ID == id)
                return root;

            foreach (Control c in root.Controls)
            {
                Control t = FindControlRecursive(c, id);
                if (t != null)
                    return t;
            }

            return null;

            
        }

        public static string GetDeleteElementScript(string radAjaxManagerClientID,
            string deleteNodeWindowUrl, string cultureName, bool destroy, bool isInvariantCulture)
        {
            return String.Concat("var deleteNodeId;\n",
                 " function openDeleteNodeWindow(nodeID) {\n",
                 " deleteNodeId = nodeID;\n",
                 " radopen('" + deleteNodeWindowUrl + "?"+ DefaultParamNames.NodeID +"=' + nodeID + '&culturename=" + cultureName + "&destroy=" + destroy + "&neutral=" + isInvariantCulture +"', 'deleteNodeWindow');\n",
                 " }\n",
                 " function deleteNodeWindowCallback(sender, eventArgs) {\n",
                 " var argument = eventArgs.get_argument();\n",
                 " Medianamik.UI.Services.LockWebService.Unlock(deleteNodeId, function() {  }, function() {  });\n",             
                 " if (argument && argument.mustReload) {\n",
                 " $find(\"" + radAjaxManagerClientID + "\").ajaxRequest(\"DeleteNodeWindowCallback\");\n",
                 " }\n",
                 " }\n");
        }

        public static string GetRowDroppingScript(string gridClientId)
        {
            return String.Concat("function onRowDropping(sender, args) {\n",
                " if (sender.get_id() == \"" + gridClientId + "\") {\n",
                " var node = args.get_destinationHtmlElement();\n",
                " if (!isChildOf('" + gridClientId + "', node)) {\n",
                " args.set_cancel(true);\n",
                " }\n",
                " }\n",
                " }\n",
                " function isChildOf(parentId, element) {\n",
                " while (element) {\n",
                " if (element.id && element.id.indexOf(parentId) > -1) {\n",
                " return true;\n",
                " }\n",
                " element = element.parentNode;\n",
                " }\n",
                " return false;\n",
                " }\n");
        }

        //Pour la création d'élément selon un autre langue 
        //Voir EnableMultiLanguageFeatures (le bouton + dans la grille)
        public static string GetCultureSelectedScript(string editPageUrl, bool hideTreeview,
            string nodeIdParamName, string returnUrl)
        {
            return String.Concat(" function onCultureSelected(sender, eventArgs) {\n",
                " var argument = eventArgs.get_argument();\n",
                " if (argument && argument.NodeId) {\n",
                " var url = '" + editPageUrl + "?hidetreeview=" + hideTreeview.ToString().ToLower() + "&" + nodeIdParamName + "=' + argument.NodeId",
                String.IsNullOrEmpty(returnUrl) ? "" : "url += " + returnUrl,
                ";\n",
                " if(argument.Culture && argument.Culture.length > 0) {\n",
                    " url += '&culture=' + argument.Culture;\n",
                " }\n",
                " location.href = url;",
                " }\n",
                " }\n");
        }

        public static string GetTypeSelectedScript(string editPageUrl, bool hideTreeview,
            string parentNodeIdParamName, string typeIdParamName, string returnUrl)
        {
            return String.Concat(" function onNodeTypeSelected(sender, eventArgs) {\n",
                " var argument = eventArgs.get_argument();\n",
                " if (argument && argument.NodeTypeId) {\n",
                " var url = '" + editPageUrl + "?" + typeIdParamName + "=' + argument.NodeTypeId + '&hidetreeview=" + hideTreeview.ToString().ToLower() + "';\n",
                String.IsNullOrEmpty(returnUrl) ? "" : "url += '" + returnUrl + "';\n",
                " if(argument.ParentNodeId) {\n",
                    " url += '&" + parentNodeIdParamName + "=' + argument.ParentNodeId;\n",
                " }\n",
                " location.href = url;",
                " }\n",
                " }\n");
        }
       
        public const string namePropertyIdentifier = "Name";

        public static HierarchicalDataItem NodeToHierarchicalDataItem(Node node, string cultureName)
        {
            return new HierarchicalDataItem
            {
                ID = node.ID,
                ParentID = node.ParentID,
                Name = GetFriendlyIdentifier(node, cultureName)
            };
        }

        public static string GetFriendlyIdentifier(Node node, string cultureName)
        {
            string friendlyIdentifier = node.ID.ToString();

            if(node.NodeTypeID == MedianamikTypes.Module)
            {
                friendlyIdentifier = Translator.Translate(ResourceSets.SiteMap, node.Instances[0].Properties[MedianamikProperties.MedianamikModuleAlias].GetValue<String>());
            }
            else{
                    if (node.Instances.Exists(cultureName))
                    {
                        if (node.Instances[cultureName].Properties.Exists(namePropertyIdentifier))
                            friendlyIdentifier = node.Instances[cultureName].Properties[namePropertyIdentifier].GetValue<String>();
                    }
                    else
                    {
                        if (node.Instances[0].Properties.Exists(namePropertyIdentifier))
                            friendlyIdentifier = node.Instances[0].Properties[namePropertyIdentifier].GetValue<String>();
                    }
            }

            return friendlyIdentifier;
        }
    }
}
